<template>
  <div class="tetris-container">
    <div class="game-area">
      <!-- 游戏主区域 -->
      <div class="game-board" ref="gameBoard" tabindex="0" @keydown="handleKeydown">
        <div v-for="(row, y) in gameMatrix" :key="y" class="board-row">
          <div v-for="(cell, x) in row" 
               :key="x" 
               :class="['board-cell', { 
                 'active': isActivePiece(x, y),
                 'filled': cell === 1,
                 [`color-${cell}`]: cell > 0
               }]">
          </div>
        </div>
      </div>

      <!-- 游戏信息面板 -->
      <div class="game-panel">
        <div class="next-piece">
          <h3>下一个</h3>
          <div class="next-piece-preview">
            <div v-for="(row, y) in nextPieceMatrix" :key="y" class="preview-row">
              <div v-for="(cell, x) in row" 
                   :key="x" 
                   :class="['preview-cell', { 
                     'filled': cell === 1,
                     [`color-${nextPiece.type}`]: cell === 1 
                   }]">
              </div>
            </div>
          </div>
        </div>

        <div class="game-stats">
          <div class="stat-item">
            <span class="stat-label">分数</span>
            <span class="stat-value">{{ score }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">等级</span>
            <span class="stat-value">{{ level }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">行数</span>
            <span class="stat-value">{{ lines }}</span>
          </div>
        </div>

        <div class="game-controls">
          <button class="control-button" @click="startGame" :disabled="isPlaying">
            开始游戏
          </button>
          <button class="control-button" @click="pauseGame" :disabled="!isPlaying">
            {{ isPaused ? '继续' : '暂停' }}
          </button>
          <button class="control-button" @click="resetGame" :disabled="isPlaying && !isPaused">
            重新开始
          </button>
        </div>

        <div class="game-instructions">
          <h3>操作说明</h3>
          <ul>
            <li>← → : 左右移动</li>
            <li>↑ : 旋转</li>
            <li>↓ : 加速下落</li>
            <li>空格 : 直接落下</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
import { initGame, createGameState } from './game'

const gameBoard = ref(null)
const gameState = ref(createGameState())

// 使用计算属性来访问游戏状态
const gameMatrix = computed(() => gameState.value.gameMatrix)
const nextPieceMatrix = computed(() => gameState.value.nextPieceMatrix)
const nextPiece = computed(() => gameState.value.nextPiece)
const score = computed(() => gameState.value.score)
const level = computed(() => gameState.value.level)
const lines = computed(() => gameState.value.lines)
const isPlaying = computed(() => gameState.value.isPlaying)
const isPaused = computed(() => gameState.value.isPaused)

let gameLoop = null
const game = initGame(gameState)

// 检查是否是活动方块
const isActivePiece = (x, y) => {
  const { currentPiece, currentX, currentY } = gameState.value
  if (!currentPiece) return false

  const pieceMatrix = currentPiece.matrix
  const pieceY = y - currentY
  const pieceX = x - currentX

  return pieceY >= 0 && pieceY < pieceMatrix.length &&
         pieceX >= 0 && pieceX < pieceMatrix[0].length &&
         pieceMatrix[pieceY][pieceX] === 1
}

// 键盘控制
const handleKeydown = (event) => {
  if (!gameState.value.isPlaying || gameState.value.isPaused) return

  switch (event.key) {
    case 'ArrowLeft':
      game.moveLeft()
      break
    case 'ArrowRight':
      game.moveRight()
      break
    case 'ArrowUp':
      game.rotate()
      break
    case 'ArrowDown':
      game.moveDown()
      break
    case ' ':
      event.preventDefault() // 防止空格键滚动页面
      game.dropDown()
      break
  }
}

// 游戏控制
const startGame = () => {
  if (gameState.value.isPlaying) return
  
  game.start()
  gameBoard.value?.focus()
  
  updateGameLoop()
}

// 更新游戏循环
const updateGameLoop = () => {
  clearInterval(gameLoop)
  const speed = Math.max(100, 800 - gameState.value.level * 100)
  gameLoop = setInterval(() => {
    if (!gameState.value.isPaused) {
      game.update()
    }
  }, speed)
}

// 监听等级变化，更新游戏速度
watch(() => gameState.value.level, (newLevel) => {
  if (gameState.value.isPlaying && !gameState.value.isPaused) {
    updateGameLoop()
  }
})

const pauseGame = () => {
  if (!gameState.value.isPlaying) return
  game.togglePause()
}

const resetGame = () => {
  clearInterval(gameLoop)
  gameLoop = null
  Object.assign(gameState.value, createGameState())
}

// 初始化游戏
onMounted(() => {
  // 添加全局键盘事件监听
  window.addEventListener('keydown', handleKeydown)
  
  // 确保游戏区域可以获得焦点
  gameBoard.value?.focus()
  
  // 防止键盘事件丢失焦点
  gameBoard.value?.addEventListener('blur', () => {
    gameBoard.value?.focus()
  })
})

// 清理
onUnmounted(() => {
  clearInterval(gameLoop)
  window.removeEventListener('keydown', handleKeydown)
})
</script>

<style scoped>
.tetris-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: var(--theme-container-bg, #1a1a1a);
}

.game-area {
  display: flex;
  gap: 20px;
  padding: 20px;
  background-color: var(--theme-bg, #2d2d2d);
  border-radius: 12px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}

.game-board {
  width: fit-content;
  height: fit-content;
  border: 2px solid var(--theme-border-color, #404040);
  background-color: var(--theme-container-bg, #1a1a1a);
  display: flex;
  flex-direction: column;
  outline: none;
  padding: 2px;
}

.board-row {
  display: flex;
  flex: 1;
}

.board-cell {
  flex: none;
  width: 30px;
  height: 30px;
  border: 1px solid var(--theme-border-color, #333);
  transition: background-color 0.1s;
}

.board-cell.active {
  background-color: var(--theme-primary-color, #4a5568);
}

.board-cell.filled {
  background-color: var(--theme-secondary-color, #2d3748);
}

.game-panel {
  width: 200px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.next-piece {
  background-color: var(--theme-container-bg, #1a1a1a);
  padding: 15px;
  border-radius: 8px;
}

.next-piece h3 {
  margin: 0 0 10px;
  color: var(--theme-text-color, #e2e8f0);
  font-size: 16px;
}

.next-piece-preview {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.preview-row {
  display: flex;
  flex: 1;
}

.preview-cell {
  flex: 1;
  border: 1px solid var(--theme-border-color, #333);
}

.preview-cell.filled {
  background-color: var(--theme-primary-color, #4a5568);
}

.game-stats {
  background-color: var(--theme-container-bg, #1a1a1a);
  padding: 15px;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: var(--theme-text-color, #e2e8f0);
}

.stat-label {
  font-size: 14px;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: var(--theme-primary-color, #60a5fa);
}

.game-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.control-button {
  padding: 10px;
  border: none;
  border-radius: 6px;
  background-color: var(--theme-primary-color, #3b82f6);
  color: white;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
}

.control-button:hover:not(:disabled) {
  background-color: var(--theme-primary-hover, #2563eb);
}

.control-button:disabled {
  background-color: var(--theme-secondary-color, #4b5563);
  cursor: not-allowed;
}

.game-instructions {
  background-color: var(--theme-container-bg, #1a1a1a);
  padding: 15px;
  border-radius: 8px;
  color: var(--theme-text-color, #e2e8f0);
}

.game-instructions h3 {
  margin: 0 0 10px;
  font-size: 16px;
}

.game-instructions ul {
  margin: 0;
  padding-left: 20px;
  font-size: 14px;
}

.game-instructions li {
  margin: 5px 0;
}

/* 方块颜色 */
.color-1 { background-color: #ef4444; }  /* 红色 */
.color-2 { background-color: #f59e0b; }  /* 橙色 */
.color-3 { background-color: #10b981; }  /* 绿色 */
.color-4 { background-color: #3b82f6; }  /* 蓝色 */
.color-5 { background-color: #8b5cf6; }  /* 紫色 */
.color-6 { background-color: #ec4899; }  /* 粉色 */
.color-7 { background-color: #14b8a6; }  /* 青色 */

/* 响应式设计 */
@media (max-width: 768px) {
  .game-area {
    flex-direction: column;
    padding: 10px;
  }

  .game-board {
    width: 100%;
    max-width: 300px;
    height: auto;
    aspect-ratio: 1/2;
  }

  .game-panel {
    width: 100%;
    max-width: 300px;
  }
}
</style> 